home *** CD-ROM | disk | FTP | other *** search
- Path: grimsel.zurich.ibm.com!usenet
- From: Keith Whittingham <wgk@zurich.ibm.com>
- Newsgroups: comp.lang.c++
- Subject: Re: casting w/ virtual base classes
- Date: Tue, 16 Apr 1996 17:01:49 -0700
- Organization: IBM Zurich Research Laboratory
- Message-ID: <317434ED.1C4F@zurich.ibm.com>
- References: <31728499.6201DD56@unisql.com> <317396ED.ABD322C@intellektik.informatik.th-darmstadt.de>
- NNTP-Posting-Host: pine.zurich.ibm.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.01 (Win16; I)
-
- Enno Sandner wrote:
- >
- > > class Derived : public virtual Base {...};
- > >
- > > Base* foo(void) {...}
- > >
- > > Derived *dp1 = foo();
- > > Derived *dp2 = (Derived *) foo();
- > >
- > > error: cast: Base* ->derived dp2*; Base is virtual base
- > > Q1: Is the double cast legal? Why? / Why not?
- >
- > It's legal -- but the result is undefined.
- > The forthcoming C++ standard provides a special cast-operator
- > for this purpose. The 'dynamic_cast'
- >
- > Derived* dp=dyanmic_cast<Derived*>(foo());
- >
- > will safely narrow the pointer (*). If the returned object
- > is not an object of a subclass of 'Dervived', the dynamic_cast
- > expression returns a null-pointer.
- >
-
- The purpose of the dynamic_cast is to downcast after checking
- that object is of the target type or, presumably, in the hierarchy:
-
- class A {} *a;
- class B: public A {} *pb;
- class C: public B {} c, *pc;
-
- a = &c;
- pb = dynamic_cast<B *> a; // not sure about this
- pc = dynamic_cast<C *> a;
-
- I have implemented this using basic C++ (i.e. convertion
- operators) so that this works with or without cast
- operators and without the need for any cast, dynamic
- or otherwise.
-
- pb = (B *)a;
- pb = a; // Works also!
-
- But I digress. The original posters question is based on the
- fact that the base class is virtual so that a cast error
- occurs which is the case and is correct. I guess it is to
- do with the implementation of virtual base classes not
- being a contiguous memory block but am not sure...
-
-
- --
- Keith Whittingham
- wgk@zurich.ibm.com
-